//
//  LoginViewController.m
//  PartyAnimal
//
//  Created by Hilary Muludiang on 4/1/12.
//  Copyright 2012 Muludiang. All rights reserved.
//

#import "LoginViewController.h"
#import "StackMob.h"
#import "LogoutViewController.h"
#import "PartyAnimalAppDelegate.h"
#import "iBacchanal.h"

@implementation LoginViewController

@synthesize emailAddress;
@synthesize loginButton;
@synthesize newUser;
@synthesize password;
@synthesize logoutViewController;


-(IBAction)cancel:(UIButton *)sender{
	[self dismissModalViewControllerAnimated:YES];
}

-(IBAction)login:(UIButton *)sender{
	
	if ([[[emailAddress text] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] > 0 &&
		[[[password text] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] > 0){
		
		if ([newUser selectedSegmentIndex] == 0){
			[self loginUser:[emailAddress text] andPassword:[password text]];
		}
		else {
			NSLog(@"New user..");
			[self createUser:[emailAddress text] andPassword:[password text]];
			
		}
	}
}


-(void)loginUser:(NSString *)withEmail andPassword:(NSString *)passwordString{
	
	NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:emailAddress.text,
						  @"username", password.text, @"password", nil];
	[[StackMob stackmob] loginWithArguments:args andCallback:^(BOOL success, id result) {
		if (success) {
			// Login Succeeded
			iBacchanal *bacchanal = [iBacchanal sharedUser];
			bacchanal.loggedIn = YES;
			bacchanal.currentUser = emailAddress.text;
			[self dismissModalViewControllerAnimated:YES];
			
		} else {
			// Login Failed
			UIAlertView *errorAlert = [[UIAlertView alloc] 
									   initWithTitle:@"Oops.." message:@"Sorry, invalid email/password combination"
									   delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[errorAlert show];
			[errorAlert release];
			NSLog(@"Login Failed: %@", result);
		}
	}];	
}


-(void)createUser:(NSString *)withEmail andPassword:(NSString *)passwordString{
	NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
	[dictionary setValue:withEmail forKey:@"username"];
	[dictionary setValue:passwordString forKey:@"password"];
	
	[[StackMob stackmob] post:@"user"
				withArguments:dictionary andCallback:^(BOOL success, id result){
					if(success){
						// Cast result to a NSDictionary* and do something with the UI
						// Alert delegates
						NSLog(@"Create user passed: %@", result);
						[self loginUser:withEmail andPassword:passwordString];
						
					}
					else {
						// Cast result to an NSError* and alert your delegates
						NSLog(@"Create user Failed: %@", result);
						
					}
				}];
}

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */


 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
	 self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel:)] autorelease];
	 //self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(submitEvent:)] autorelease];

 }


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[logoutViewController release];
	[newUser release];
	[loginButton release];
	[emailAddress release];
	[password release];
    [super dealloc];
}


@end
